package com.huawei.hmsdemo10086.Activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.huawei.hms.hwid.I;
import com.huawei.hmsdemo10086.Adapter.GoodsAdapter;
import com.huawei.hmsdemo10086.Adapter.VideoAdapter;
import com.huawei.hmsdemo10086.POJO.Goods;
import com.huawei.hmsdemo10086.POJO.GoodsType;
import com.huawei.hmsdemo10086.POJO.Result;
import com.huawei.hmsdemo10086.POJO.Shop;
import com.huawei.hmsdemo10086.R;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class GoodsActivity extends AppCompatActivity {

    private Result<List<Goods>>  result;
    private Result<List<GoodsType>>  result1;
    private int shopid;
    private Spinner spinner;
    private Spinner sortSpinner;
    private List<Goods> datas;
    private GoodsAdapter adapter;
    private List<String> types;
    private ArrayAdapter<String> arrayAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods);
        spinner = (Spinner)findViewById(R.id.type_spinner);
        sortSpinner = (Spinner)findViewById(R.id.sort_spinner);
        TextView mTitleTextView = (TextView) this.findViewById(R.id.text_title);
        mTitleTextView.setText("商品列表");
        Button back = (Button)this.findViewById(R.id.button_backward);
        datas = new ArrayList<Goods>();
        types = new ArrayList<String>();
        Intent intent = this.getIntent();
        shopid = intent.getIntExtra("shopid",-1);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GoodsActivity.this,ShopActivity.class);
                startActivity(intent);
                finish();
            }
        });

        getTypes();
        arrayAdapter = new ArrayAdapter<String>(GoodsActivity.this,android.R.layout.simple_spinner_item,types);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(arrayAdapter);


        result = null;
        getGoods();

        while (datas==null){
            Log.d("wait", "wait goods init");
        }

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.goods_recycle_view);
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new GoodsAdapter(this,datas);

        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickLitener(new VideoAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(GoodsActivity.this,GoodsDetailsActivity.class);
                intent.putExtra("goods",result.getData().get(position));

                startActivity(intent);
            }

            @Override
            public void onCollection(View view, int position) {

            }
        });

        spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {//选择item的选择点击监听事件
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                int type = 0;
                datas.clear();
                for(int i = 0 ;i < result1.getData().size() ; i++)
                {
                    if(arrayAdapter.getItem(arg2).equals(result1.getData().get(i).getType_name()))
                    {
                        type = result1.getData().get(i).getType();
                        break;
                    }
                }

                for(int i = 0 ; i < result.getData().size() ; i++)
                {
                    if(type == 0 || Integer.parseInt(result.getData().get(i).getType()) == type)
                    {
                        datas.add(result.getData().get(i));
                    }
                }
                adapter.notifyDataSetChanged();
                arrayAdapter.notifyDataSetChanged();
            }

            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });


        sortSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {//选择item的选择点击监听事件
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                if(arg2 == 0)
                {
                    Collections.sort(datas, new Comparator<Goods>() {
                        public int compare(Goods arg0, Goods arg1) {
                            return arg0.getName().compareTo(arg1.getName());
                        }
                    });
                }
                else if(arg2 == 1)
                {
                    Collections.sort(datas, new Comparator<Goods>() {
                        public int compare(Goods arg0, Goods arg1) {
                            return (int) (arg0.getPrice() - arg1.getPrice());
                        }
                    });
                }
                else if(arg2 == 2)
                {
                    Collections.sort(datas, new Comparator<Goods>() {
                        public int compare(Goods arg0, Goods arg1) {
                            return (int) (arg1.getPrice() - arg0.getPrice());
                        }
                    });
                }
                arrayAdapter.notifyDataSetChanged();
                adapter.notifyDataSetChanged();
            }

            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });

    }

    private void getTypes()
    {

        String url = "http://10.0.2.2:8443/api/getAllTypes";
        OkHttpClient mOkHttpClient = new OkHttpClient();


        Request request = new Request.Builder().url(url).get().build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("测试", e+"");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                Gson gson = new Gson();
                String rep = response.body().string();


                Type type = new TypeToken<Result<List<GoodsType>>>(){}.getType();
                result1 = gson.fromJson(rep,type);
                for(int i = 0 ; i < result1.getData().size() ; i++)
                {
                    types.add(result1.getData().get(i).getType_name());
                    System.out.println(types.get(i));
                }

            }
        });
    }

    private void getGoods()
    {

        String url = "http://10.0.2.2:8443/api/listGoods";
        OkHttpClient mOkHttpClient = new OkHttpClient();

        String json = "{\n" +
                "  \"shop_id\": \"" + shopid + "\"\n" +
                "}";
        Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("测试", e+"");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                Gson gson = new Gson();
                String rep = response.body().string();
                System.out.println(rep);

                Type type = new TypeToken<Result<List<Goods>>>(){}.getType();
                result = gson.fromJson(rep,type);
                for(int i = 0 ; i < result.getData().size() ; i++)
                {
                    if(result.getData().get(i).getNum() == 0)
                    {
                        result.getData().remove(result.getData().get(i));
                        i--;
                    }
                    else
                    {
                        System.out.println(result.getData().get(i).toString());
                        datas.add(result.getData().get(i));
                    }

                    //System.out.println(result.getData().get(i).toString());
                }
            }
        });
    }
}